package com.enqualcomm.kids.mvp.chat;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.enqualcomm.kids.R;
import com.enqualcomm.kids.bean.AbstractorMessage;
import com.enqualcomm.kids.bean.ChatMsg;
import com.enqualcomm.kids.view.ImageUtils;
import com.facebook.drawee.view.SimpleDraweeView;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import common.utils.NetUtil;

/**
 * Created by yinzhiqun on 2015/6/8.
 */
public class ChatMsgAdapter extends BaseAdapter implements PlayerObserver {
    private ArrayList<ChatMsg> msgs;
    private final LayoutInflater inflater;
    private IPlayerManager playerManager;
    private Context context;
    private Handler mHandler;
    private AudioManager am;
    private ChatViewController controller;
    private View currentPlayingItem;
    private final AnimationDrawable audio_playing_left;
    private final AnimationDrawable audio_playing_right;
    private boolean speakerOn;

    private Drawable playing_left3;
    private Drawable playing_right3;

    public ChatMsgAdapter(Context context, ArrayList<ChatMsg> msgs) {
        this.msgs = msgs;
        this.context = context;
        inflater = LayoutInflater.from(context);
        audio_playing_left = (AnimationDrawable) context.getResources().getDrawable(R.drawable.audio_playing_left);
        audio_playing_right = (AnimationDrawable) context.getResources().getDrawable(R.drawable.audio_playing_right);

        playing_right3 = context.getResources().getDrawable(R.drawable.audio_playing_right3);
        playing_left3 = context.getResources().getDrawable(R.drawable.audio_playing_left3);
        processDate();
    }


    public void setData(ArrayList<ChatMsg> msgs) {
        this.msgs = msgs;
        processDate();
        notifyDataSetChanged();
    }

    /**
     * 把消息添加到末尾（新消息）
     *
     * @param newMsgs
     */
    public void addLast(ArrayList<ChatMsg> newMsgs) {
        if (msgs != null) {
            msgs.addAll(newMsgs);
        } else {
            msgs = newMsgs;
        }
        processDate();
        notifyDataSetChanged();
    }

    /**
     * 把消息加到最前面（历史消息）
     *
     * @param historyMsgs
     */
    public void addFirst(ArrayList<ChatMsg> historyMsgs) {
        if (msgs != null) {
            historyMsgs.addAll(msgs);
        }
        msgs = historyMsgs;
        processDate();
        notifyDataSetChanged();
    }

    public void processDate() {
        long lastShowingDate = 0;//最后一个显示的时间
        for (ChatMsg msg : msgs) {
            if (msg.time - lastShowingDate > 300000) {//如果大于5分钟
                msg.showDate = true;
                lastShowingDate = msg.time;
                if (msg.displayTime == null) {
                    if (DateUtils.isToday(msg.time)) {
                        //是当天，显示时分秒
                        msg.displayTime = context.getString(R.string.today) + new SimpleDateFormat(" HH:mm").format(new Date(msg.time));
                    } else {
                        msg.displayTime = DateFormat.getDateInstance(DateFormat.LONG, context.getResources().getConfiguration().locale).format(new Date(msg.time));
                    }
                }
            } else {
                msg.showDate = false;
            }

        }
    }

    /**
     * 某一条消息状态发生变化(status,duration)
     *
     * @param current
     */
    public void updateMsg(ChatMsg current) {
        if (msgs != null) {
            for (ChatMsg old : msgs) {
                if (old._id.equals(current._id)) {
                    old.status = current.status;
                    old.duration = current.duration;
                    notifyDataSetChanged();
                    break;
                }
            }
        }
    }

    /**
     * 某一条消息状态发生变化(status,duration)
     *
     * @param current
     */
    public void updateMsg2(ChatMsg current) {
        if (msgs != null) {
            for (ChatMsg old : msgs) {
                if (old._id.equals(current._id)) {
                    old.status = current.status;
                    old.duration = current.duration;
                    old.status = current.status;
                    notifyDataSetChanged();
                    break;
                }
            }
        }
    }


    /**
     * 获取当前最后一条消息的id
     *
     * @return
     */
    public String getMaxId() {
        return msgs == null || msgs.isEmpty() ? null : msgs.get(msgs.size() - 1)._id;
    }


    @Override
    public int getCount() {
        return msgs == null ? 0 : msgs.size();
    }

    @Override
    public Object getItem(int i) {
        return msgs.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    public void init(IPlayerManager playerManager, Handler mHandler, ChatViewController controller, AudioManager am) {
        this.playerManager = playerManager;
        this.mHandler = mHandler;
        this.controller = controller;
        this.am = am;
        this.speakerOn = true;
        am.setMode(AudioManager.MODE_NORMAL);
        am.setSpeakerphoneOn(true);
        playerManager.addObserver(this);
    }


    @Override
    public void update(int status, IPlayerManager iPlayerManager) {
        switch (status) {//播放状态改变回调
            case PlayerObserver.PLAYING:
                updatePlayingState(currentPlayingItem, true);
                break;
            case PlayerObserver.IDLE://暂停播放，播放完成
                updatePlayingState(currentPlayingItem, false);
                playingItemId = null;
                break;
            case PlayerObserver.ERROR:
                updatePlayingState(currentPlayingItem, false);
                playingItemId = null;
                break;
        }
    }


    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        final ChatMsg chatMsg = msgs.get(position);

        //===================item样式太多，不用缓存了====================================================

        if (chatMsg.type == ChatMsg.TYPE_VOICE || chatMsg.type == ChatMsg.TYPE_VOICE2) {//语音类型
            convertView = inflater.inflate(chatMsg.isReceived ? R.layout.chatting_item_left : R.layout.chatting_item_right, null);
            bindDataVoice(convertView, chatMsg);
        } else {//图片类型
            convertView = inflater.inflate(R.layout.chatting_item_img_left, null);//目前只能收不能发
            bindDataImage(convertView, chatMsg);
        }

        return convertView;
    }


    private void bindDataVoice(View convertView, final ChatMsg chatMsg) {
        TextView chat_item_sendtime_tv = (TextView) convertView.findViewById(R.id.chat_item_sendtime_tv);
        if (chatMsg.showDate) {
            chat_item_sendtime_tv.setText(chatMsg.displayTime);
            chat_item_sendtime_tv.setVisibility(View.VISIBLE);
        } else {
            chat_item_sendtime_tv.setVisibility(View.GONE);
        }

        SimpleDraweeView chat_item_userhead_iv = (SimpleDraweeView) convertView.findViewById(R.id.chat_item_userhead_iv);
        if (chatMsg.isReceived) {
            chat_item_userhead_iv.setImageBitmap(BitmapFactory.decodeFile(chatMsg.picPath));
            chat_item_userhead_iv.setImageURI(chatMsg.headUri);
        } else {
            chat_item_userhead_iv.setImageURI(chatMsg.headUri);
        }

        TextView chat_item_content_tv = (TextView) convertView.findViewById(R.id.chat_item_content_tv);
        View chat_item_loading_pb = convertView.findViewById(R.id.chat_item_loading_pb);
        View chat_item_resend_iv = convertView.findViewById(R.id.chat_item_resend_iv);
        View chat_item_red_point = convertView.findViewById(R.id.chat_item_red_point);
        View chat_playstate_iv = convertView.findViewById(R.id.chat_playstate_iv);

        switch (chatMsg.status) {
            case ChatMsg.STATUS_LOADING://显示正在加载进度条
                chat_item_loading_pb.setVisibility(View.VISIBLE);
                chat_item_resend_iv.setVisibility(View.GONE);
                chat_playstate_iv.setVisibility(View.GONE);
                chat_item_content_tv.setText("");
                chat_item_red_point.setVisibility(View.GONE);
                break;
            case ChatMsg.STATUS_NET_ERROR://显示按钮，点击重发、重新获取
                chat_item_loading_pb.setVisibility(View.GONE);
                chat_item_resend_iv.setVisibility(View.VISIBLE);
                chat_item_resend_iv.setOnClickListener(new ReSendListener(chatMsg));//重新发送
                chat_playstate_iv.setVisibility(View.GONE);
                chat_item_content_tv.setText("");
                chat_item_red_point.setVisibility(View.GONE);
                break;
            case ChatMsg.STATUS_OK://正常显示持续时间，点击可播放
                chat_item_loading_pb.setVisibility(View.GONE);
                chat_item_resend_iv.setVisibility(View.GONE);
                chat_playstate_iv.setVisibility(View.VISIBLE);
                chat_item_content_tv.setText(getDurationStr(chatMsg.duration, chatMsg.isReceived));
                chat_item_red_point.setVisibility(chatMsg.isread == ChatMsg.ISREAD_UNREAD ? View.VISIBLE : View.GONE);


                chat_playstate_iv.setTag(chatMsg.isReceived);
                chat_item_content_tv.setOnClickListener(new ClickListener(chatMsg, chat_playstate_iv));//点击播放
                chat_item_content_tv.setOnLongClickListener(new LongClickListener(chatMsg));//长按弹出菜单

                updatePlayingState(chat_playstate_iv, chatMsg._id.equals(playingItemId));
                if (chatMsg.type == ChatMsg.TYPE_VOICE2) {//群发标志,注意只有手表发过来的才有
                    convertView.findViewById(R.id.chat_item_category).setVisibility(View.VISIBLE);
                }
                break;
        }

    }

    private void bindDataImage(View convertView, final ChatMsg chatMsg) {

        TextView chat_item_sendtime_tv = (TextView) convertView.findViewById(R.id.chat_item_sendtime_tv);
        if (chatMsg.showDate) {
            chat_item_sendtime_tv.setText(chatMsg.displayTime);
            chat_item_sendtime_tv.setVisibility(View.VISIBLE);
        } else {
            chat_item_sendtime_tv.setVisibility(View.GONE);
        }

        ImageView chat_item_userhead_iv = (ImageView) convertView.findViewById(R.id.chat_item_userhead_iv);
        if (chatMsg.isReceived || new File(chatMsg.picPath).exists()) {//用户的头像比较乱，有可能在assets，有可能在sd卡
            chat_item_userhead_iv.setImageBitmap(BitmapFactory.decodeFile(chatMsg.picPath));
        } else {
            try {
                chat_item_userhead_iv.setImageBitmap(BitmapFactory.decodeStream(context.getAssets().open(chatMsg.picPath)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //TODO
        TextView chat_item_content_tv = (TextView) convertView.findViewById(R.id.chat_item_content_tv);
        View chat_item_resend_iv = convertView.findViewById(R.id.chat_item_resend_iv);
        ImageView chat_img_msg_iv = (ImageView) convertView.findViewById(R.id.chat_img_msg_iv);
        View chat_item_loading_pb = convertView.findViewById(R.id.chat_item_loading_pb);
        switch (chatMsg.status) {
            case ChatMsg.STATUS_LOADING://正在接收
                chat_item_loading_pb.setVisibility(View.VISIBLE);
                chat_item_content_tv.setText("");//远程拍照启动，图片上传中\n请稍后......
                chat_item_resend_iv.setVisibility(View.GONE);
                break;
            case ChatMsg.STATUS_NET_ERROR://接收失败
                chat_item_loading_pb.setVisibility(View.GONE);
                chat_item_content_tv.setText("");//远程拍照失败，点击重试
                chat_item_resend_iv.setVisibility(View.VISIBLE);
                chat_item_resend_iv.setOnClickListener(new ReSendListener(chatMsg));
                break;
            case ChatMsg.STATUS_OK://接收成功，正常显示图片
                chat_item_loading_pb.setVisibility(View.GONE);
                chat_item_content_tv.setVisibility(View.GONE);
                chat_item_resend_iv.setVisibility(View.GONE);
                chat_img_msg_iv.setVisibility(View.VISIBLE);

                Bitmap imageBitmap = ImageUtils.getImageBitmap(128, 128, chatMsg.content);
                chat_img_msg_iv.setImageBitmap(imageBitmap);
                break;
        }


    }


    class ReSendListener implements View.OnClickListener {
        private ChatMsg msg;

        public ReSendListener(ChatMsg msg) {
            this.msg = msg;
        }

        @Override
        public void onClick(View view) {
            if (mHandler != null && NetUtil.checkNet(context)) {
                msg.status = ChatMsg.STATUS_LOADING;
                notifyDataSetChanged();
                if (msg.isReceived) {
                    ChatUtil.getVoice(context, msg, mHandler);
                } else {
                    ChatUtil.sendVoice(context, msg, mHandler);
                }
            }
        }
    }

    private String playingItemId;

    class ClickListener implements View.OnClickListener {
        private ChatMsg msg;
        private View chat_playstate_iv;

        public ClickListener(ChatMsg msg, View chat_playstate_iv) {
            this.msg = msg;
            this.chat_playstate_iv = chat_playstate_iv;
        }

        @Override
        public void onClick(View view) {
            if (playerManager != null && msg.status == ChatMsg.STATUS_OK) {//没有正常获取/发送，不允许播放
//                if (msg.content.equals(playerManager.getCurrentFilePath())){
                if (msg._id.equals(playingItemId)) {
                    playerManager.stop();
                } else {

                    //先把上一个item改为没有播放的状态
                    updatePlayingState(currentPlayingItem, false);
                    currentPlayingItem = chat_playstate_iv;
                    playingItemId = msg._id;

                    playerManager.start(msg.content);

                    if (msg.isReceived && msg.isread == ChatMsg.ISREAD_UNREAD) {//如果是别人发过来的，并且还是未读状态，标记为已读
                        ChatUtil.markRead(msg._id, context);
                        msg.isread = ChatMsg.ISREAD_READ;
                        notifyDataSetChanged();
                    }
                }
            }
        }
    }

    public boolean isSpeakerOn() {
        return speakerOn;
    }


    class LongClickListener implements View.OnLongClickListener {
        private ChatMsg msg;

        public LongClickListener(ChatMsg msg) {
            this.msg = msg;
        }

        @Override
        public boolean onLongClick(View view) {
            if (msgs != null && playingItemId == null) {//正在播放时，不让弹出对话框
                String str = speakerOn ? context.getString(R.string.play_mode_call) : context.getString(R.string.play_mode_normal);

                new ChatDialog(context, str, new ChatDialog.CallBack() {
                    @Override
                    public void onClick1() {
                        if (speakerOn) {
                            speakerOn = false;
                            controller.showEar(); //显示title耳朵图标

                            am.setMode(AudioManager.MODE_IN_CALL);
                            am.setSpeakerphoneOn(false);
                        } else {
                            speakerOn = true;
                            controller.hideEar();//隐藏

                            am.setMode(AudioManager.MODE_NORMAL);
                            am.setSpeakerphoneOn(true);
                        }
                    }

                    @Override
                    public void onClick2() {
                        ChatUtil.deleteMsg(msg.content, msg._id, context);
                        msgs.remove(msg);
                        notifyDataSetChanged();
                        controller.updateClearBtn(msgs.size());
                    }
                }).show();
            }
            return false;
        }
    }

    public void updatePlayingState(View iv, boolean isPlaying) {
        if (iv != null) {
            //根据isPlying设置不同的图片
            boolean isReceived = (boolean) iv.getTag();
            if (isReceived) {
                //左边，绿色背景
                if (isPlaying) {
                    iv.setBackgroundDrawable(audio_playing_left);
                    audio_playing_left.start();
                } else {
                    Drawable background = iv.getBackground();
                    if (background instanceof AnimationDrawable) {
                        ((AnimationDrawable) background).stop();
                    }
//                    iv.setBackgroundResource(R.drawable.audio_playing_left3);
                    iv.setBackgroundDrawable(playing_left3);
                }
            } else {
                //右边，蓝色背景
                if (isPlaying) {
                    iv.setBackgroundDrawable(audio_playing_right);
                    audio_playing_right.start();
                } else {
                    Drawable background = iv.getBackground();
                    if (background instanceof AnimationDrawable) {
                        ((AnimationDrawable) background).stop();
                    }
//                    iv.setBackgroundResource(R.drawable.audio_playing_right3);
                    iv.setBackgroundDrawable(playing_right3);
                }
            }
        }
    }

    public void setCurrentPlayingItem(View currentPlayingItem) {
        updatePlayingState(currentPlayingItem, false);
        this.currentPlayingItem = currentPlayingItem;
    }

    public void removeMessage(AbstractorMessage msg) {
        msgs.remove(msg);
    }

    public boolean isMessageListNull(){
        return msgs == null?false:true;
    }
    public void updateClearMessage() {
        controller.updateClearBtn(msgs.size());
    }

    private String getDurationStr(int duration, boolean left) {
        String str = null;
        switch (duration) {
            case 0://如果发生异常，就会是0
                str = "0\"";
                break;
            case 1:
                str = left ? "        1\"" : "1\"        ";
                break;
            case 2:
                str = left ? "          2\"" : "2\"          ";
                break;
            case 3:
                str = left ? "            3\"" : "3\"            ";
                break;
            case 4:
                str = left ? "              4\"" : "4\"              ";
                break;
            case 5:
                str = left ? "                5\"" : "5\"                ";
                break;
            case 6:
                str = left ? "                 6\"" : "6\"                 ";
                break;
            case 7:
                str = left ? "                   7\"" : "7\"                   ";
                break;
            case 8:
                str = left ? "                     8\"" : "8\"                     ";
                break;
            case 9:
                str = left ? "                       9\"" : "9\"                       ";
                break;
            case 10:
                str = left ? "                         10\"" : "10\"                         ";
                break;
            case 11:
                str = left ? "                          11\"" : "11\"                          ";
                break;
            case 12:
                str = left ? "                           12\"" : "12\"                           ";
                break;
            case 13:
                str = left ? "                            13\"" : "13\"                            ";
                break;
            case 14:
                str = left ? "                             14\"" : "14\"                             ";
                break;
            default:
                str = left ? "                              15\"" : "15\"                              ";
                break;
        }
        return str;
    }
}
